package com.share.device.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.share.common.core.exception.ServiceException;
import com.share.device.service.IMapService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Objects;

/**
 * @author ZhouShuang
 * @version 17
 * @Title
 * @date 2025/10/14 上午9:01
 */
@Service
@RequiredArgsConstructor
public class MapServiceImpl implements IMapService {

    private final RestTemplate restTemplate;
    @Value("${tencent.map.key}")
    private String key;

    @Override
    public JSONObject calculateLatLng(String keyword) {
        String url = "https://apis.map.qq.com/ws/geocoder/v1/?address={address}&key={key}";
        Map<String, String> params = Map.of("address", keyword, "key", key);
        JSONObject response = restTemplate.getForObject(url, JSONObject.class, params);
        if (Objects.requireNonNull(response).getIntValue("status") != 0) {
            throw new ServiceException("地图解析异常");
        }

        //返回第一条最佳路线
        return response.getJSONObject("result").getJSONObject("location");
    }

    /**
     * 计算当前位置到门店的距离
     *
     * @param startLongitude
     * @param startLatitude
     * @param endLongitude
     * @param endLatitude
     * @return
     */
    @Override
    public Double calculateDistance(String startLongitude, String startLatitude, String endLongitude, String endLatitude) {

        String url = "https://apis.map.qq.com/ws/direction/v1/driving/?from={from}&to={to}&key={key}";

        Map<String, String> params = Map.of("from", startLatitude + "," + startLongitude,
                "to", endLatitude + "," + endLongitude,
                "key", key);
        JSONObject jsonObject = restTemplate.getForObject(url, JSONObject.class, params);

        if (Objects.requireNonNull(jsonObject).getIntValue("status") != 0) {
            System.out.println(jsonObject.toJSONString());
            throw new ServiceException("地图服务调用失败");
        }

        //返回第一条最佳路线
        JSONObject route = jsonObject.getJSONObject("result").getJSONArray("routes").getJSONObject(0);

        return route.getBigDecimal("distance").doubleValue();
    }
}
